﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using FlexySys.Common.Attributes;
using FlexySys.Common.Items;

namespace FlexySys.Common.Items
{
    /* public class ControlType
     {
         public Type ControlType { get; set; }
         public IEnumerable< PropertyInfo> 
     }*/

    public class ControlFactory : IControlFactory
    {
        public Page Page { get; set; }

        private static Dictionary<string, Type> controlStorage = new Dictionary<string, Type>();

        public static void Init(Assembly asm)
        {
            var Types = asm.GetTypes();
            foreach (var type in Types)
            {
                var attribute = type.GetCustomAttribute<CommonControlAttribute>();
                if (attribute != null)
                {
                    controlStorage.Add(attribute.Type, type);
                }
            }


        }

        public object CreateControl(string controlType)
        {
            Control control;
            if (!controlStorage.ContainsKey(controlType))
                return null;

            Type type = controlStorage[controlType];
            var attribute = type.GetCustomAttribute<CommonControlAttribute>();

            if (!string.IsNullOrEmpty(attribute.Path))
            {
                control = Page.LoadControl(attribute.Path);
            }
            else
            {
                control = (Control)Activator.CreateInstance(type);
            }





            return control;
        }


        public string[] ControlPropeties(Type controlType)
        {
            var attribute = controlType.GetCustomAttribute<CommonControlAttribute>();
            if (string.IsNullOrEmpty(attribute.Properties))
            {
                return null;
            }

            return attribute.Properties.Split(',');
        }
    }
}
